﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using BO.Infrastructure.StaticData;
using BO.Infrastructure.Utils;
using BugManager;
using Utilities.Entities;

namespace GUI.Controls.News
{
    public partial class NewsZoneContent : System.Web.UI.UserControl
    {
        private const string ThreadFormat = "<h3 class=\"prop_thread\"><a href=\"{0}\" title=\"{2}\">{1}</a></h3>";

        private const string PublishDateFormat = "<p class=\"prop_publishinfo\"><b><span>{0}</span></b></p>";
        private const string LiFormat =
            "<li>{4}" +
            "<div class=\"scope clearfix\">" +
            "{5}" +
            "<h2><a href=\"{0}\" title=\"{2}\" class=\"prop_title\">{1}</a></h2>" +
            "{3}" +
            "{6}" +
            "</div></li>";
        private const int ImageWidth = 140;
        private const int ImageHeight = 105;
        private const int TopRelateNews = 3;
        private const string RelateNewsFormat = "<ul class=\"relation_news fr\">{0}</ul>";

        private const string RelateNewsItemFormat =
            "<li><a href=\"{0}\" title=\"{2}\"><span class=\"liststyle3 sprite fl\"></span>{1}</a></li>";

        public bool DataBind(DataTable dt, bool displayPublishedDate = true, bool displayRelateNews = true, int imageWidth = ImageWidth, int imageHeight = ImageHeight, int numberOfVisibleItem = 99, DataTable[] arrRelateNews = null)
        {
            if (dt != null && dt.Rows.Count > 0)
            {
                var sb = new StringBuilder();
                var containsColumnThread = dt.Columns.Contains(SqlConstants.Tag.ThreadId) &&
                                           dt.Columns.Contains(SqlConstants.Tag.ThreadName);
                var containsColumnRelationNews = dt.Columns.Contains(SqlConstants.NewsPublish.NewsRelation);
                displayRelateNews = displayRelateNews && (arrRelateNews != null || containsColumnRelationNews);
                for (var i = 0; i < Math.Min(dt.Rows.Count, numberOfVisibleItem); i++)
                {
                    var r = dt.Rows[i];
                    string relateNews;
                    try
                    {
                        relateNews = displayRelateNews
                                         ? arrRelateNews != null && arrRelateNews[i] != null
                                               ? BuildRelateNews(arrRelateNews[i])
                                               : containsColumnRelationNews
                                                    ? BuildRelateNews(r[SqlConstants.NewsPublish.NewsRelation].ToString())
                                                    : string.Empty

                                         : string.Empty;
                    }
                    catch (ArgumentOutOfRangeException)
                    {
                        relateNews = string.Empty;
                    }

                    var avatar = PresentationUtils.Photo.BuildNewsAvatar(r, imageWidth, imageHeight, lazyLoad: true);
                    sb.AppendFormat(LiFormat,
                                    r[SqlConstants.NewsPublish.Url],
                                    r[SqlConstants.NewsPublish.Title],
                                    r[SqlConstants.NewsPublish.EncodedTitle],
                                    displayPublishedDate
                                        ? BuildPublishedDate(
                                            PresentationUtils.Object2DateTime(
                                                r[SqlConstants.NewsPublish.DistributionDate].ToString()))
                                        : string.Empty,
                                    avatar,

                                    containsColumnThread &&
                                    string.IsNullOrEmpty(r[SqlConstants.Tag.ThreadName].ToString())
                                        ? BuildThread(r)
                                        : string.Empty,
                                    relateNews);
                }
                ltrData.Text = sb.ToString();
                return true;
            }
            return false;
        }

        private string BuildRelateNews(DataTable dataTable)
        {

            if (dataTable != null && dataTable.Rows.Count > 0)
            {
                var sb = new StringBuilder();
                foreach (DataRow r in dataTable.Rows)
                {
                    sb.AppendFormat(RelateNewsItemFormat, r[SqlConstants.NewsPublish.Url], r[SqlConstants.NewsPublish.Title],
                                    PresentationUtils.EnCode(r[SqlConstants.NewsPublish.Title].ToString()));
                }
                return string.Format(RelateNewsFormat, sb);
            }
            return string.Empty;
        }

        private static string BuildRelateNews(string json)
        {
            if (!string.IsNullOrEmpty(json))
            {
                var relateNews = PresentationUtils.JsonToObject<NewsObject[]>(json);
                return BuildRelateNews(relateNews);
            }
            return string.Empty;
        }

        private static string BuildThread(DataRow r)
        {
            try
            {
                var threadId = PresentationUtils.Object2Integer(r[SqlConstants.Tag.ThreadId].ToString());
                return string.Format(ThreadFormat,
                                     PresentationUtils.UrlBuilder.BuildThreadUrl(threadId,
                                                                                 r[SqlConstants.Tag.ThreadName].ToString
                                                                                     ()),
                                     r[SqlConstants.Tag.ThreadName],
                                     PresentationUtils.EnCode(r[SqlConstants.Tag.ThreadName].ToString()));
            }
            catch (Exception ex)
            {
                ErrorManager.Log("NewsZone.ascx", "BuildThread", ex.ToString());
            }
            return string.Empty;
        }

        private static string BuildPublishedDate(DateTime dateTime)
        {
            return string.Format(PublishDateFormat, dateTime.ToString("dd/MM/yyyy HH:mm"));
        }

        public void DataBind(List<NewsObject> listNews, int imageWidth, int imageHeight, bool bindRelateNews)
        {
            if (listNews != null && listNews.Count > 0)
            {
                var sb = new StringBuilder();
                foreach (var newsObject in listNews)
                {
                    var avatar = PresentationUtils.Photo.BuildPhoto(newsObject.Avatar, newsObject.Title, newsObject.Url, imageWidth, imageHeight, lazyLoad: true);
                    var relateNews = BuildRelateNews(newsObject.RelateNews);
                    sb.AppendFormat(
                        LiFormat,
                        newsObject.Url,
                        newsObject.Title,
                        PresentationUtils.EnCode(newsObject.Title),
                        string.Empty, //publishedDate
                        avatar,
                        string.Empty,
                        relateNews); //thread);
                }
                ltrData.Text = sb.ToString();
            }

        }

        private static string BuildRelateNews(NewsObject[] relateNews)
        {
            if (relateNews != null && relateNews.Length > 0)
            {
                var sb = new StringBuilder();
                foreach (var newsObject in relateNews.Take(Math.Min(relateNews.Length, TopRelateNews)))
                {
                    sb.AppendFormat(RelateNewsItemFormat, newsObject.Url, newsObject.Title,
                                    PresentationUtils.EnCode(newsObject.Title));
                }
                return string.Format(RelateNewsFormat, sb);
            }
            return string.Empty;
        }

    }
}